package com.yutian.example.demo.forum.mapper;

import com.yutian.example.demo.forum.dao.model.Topic;
import com.yutian.example.demo.forum.dao.model.req.TopicPageReqDO;
import com.yutian.example.demo.forum.dao.model.rsp.TopicPageRspDO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 1.使用xml来配置
 * 2.用script标签包围，然后像xml语法一样书写
 */
@Mapper
//@Repository
public interface TopicMapper {
    @Select("SELECT id,title,msg from t_topic WHERE id=#{id}")
    Topic get(@Param("id") Long id);


    @Select("<script>"
            + "SELECT id,title,msg FROM t_topic WHERE 1=1 "
            + "<if test=\"titleLike != null and titleLike != ''\"> AND title like CONCAT('%',#{titleLike},'%') </if>"
            + "</script>")
    List<Topic> list(@Param("titleLike") String titleLike);

    @Insert("insert into t_topic (title,msg) values (#{t.title}, #{t.msg})")
    @Options(useGeneratedKeys = true, keyProperty = "t.id") // 注入t.id自增主键，返回行数
    long insert(@Param("t") Topic topic);


    @Select("<script>"
            + "SELECT id,title,msg FROM t_topic where id in "
            + "<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')'>#{item}</foreach>"
            + "</script>")
    List<Topic> listByIds(@Param("ids") List<Long> ids);

    @Select("<script>"
            + "SELECT count(1) AS number FROM t_topic WHERE 1=1 "
            + "<if test=\"req.title != null and req.title != ''\"> AND title=#{req.title} </if>"
            + "</script>")
    long count(@Param("req") TopicPageReqDO req);

    @Select("<script>"
            + "SELECT id,title,msg FROM t_topic WHERE 1=1 "
            + "<if test=\"req.title != null and req.title != ''\"> AND title=#{req.title} </if>"
            + "ORDER BY ${req.sortSql} "
            + "LIMIT #{req.offset}, #{req.pageSize} "
            + "</script>")
    List<TopicPageRspDO> page(@Param("req") TopicPageReqDO req);

    /**
     * mappers/TopicMapper.xml
     * @param id
     * @return
     */
    int deleteById(@Param("id") Long id);
}